<template>
  <div class="all-tools-demo">
    <h1>全量工具函数演示（全局 $tool）</h1>
    
    <!-- 目录导航 -->
    <div class="toc-container">
      <h2>目录导航</h2>
      <div class="toc-grid">
        <div 
          v-for="(category, index) in categories" 
          :key="index"
          class="toc-item"
          @click="scrollToSection(category.id)"
        >
          {{ index + 1 }}. {{ category.name }}
        </div>
      </div>
      
      <!-- 子目录导航 -->
      <div class="toc-sub-grid">
        <div 
          v-for="(subCategory, subIndex) in subCategories" 
          :key="subIndex"
          class="toc-sub-item"
          @click="scrollToSection(subCategory.id)"
        >
          {{ subCategory.parentIndex + 1 }}.{{ subCategory.subIndex + 1 }} {{ subCategory.name }}
        </div>
      </div>
    </div>
    
    <div class="demo-container">
      <!-- 1. 数字操作 -->
      <section class="demo-card" id="数字操作">
        <h2>1. 数字操作</h2>
        
        <div class="demo-sub-card" id="随机数生成">
          <h3>1.1 生成 [min, max] 随机整数</h3>
          <div class="demo-item">
            <p>功能：生成指定范围内的随机整数（包含min和max）</p>
            <input v-model.number="numMin" type="number" placeholder="min（如1）">
            <input v-model.number="numMax" type="number" placeholder="max（如100）">
            <button @click="handleRandomNum">生成</button>
            <p class="result">结果：{{ randomNumVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="数字格式化">
          <h3>1.2 数字千分位格式化</h3>
          <div class="demo-item">
            <p>功能：将数字转换为带千分位分隔符的字符串（如1234567 → "1,234,567"）</p>
            <input v-model="thousandInput" placeholder="输入数字/字符串（如1234567）">
            <button @click="handleThousandFormat">格式化</button>
            <p class="result">结果：{{ thousandVal }}</p>
          </div>
          
          <h3>1.3 数字格式化为指定位数小数</h3>
          <div class="demo-item">
            <p>功能：保留数字指定的小数位数（自动四舍五入）</p>
            <input v-model.number="formatNumInput" type="number" placeholder="输入数字（如123.456）">
            <input v-model.number="formatDigitsInput" type="number" placeholder="小数位数（如2）">
            <button @click="handleFormatNumber">格式化</button>
            <p class="result">结果：{{ formatNumResult }}</p>
          </div>
          
          <h3>1.4 数字格式化为货币形式</h3>
          <div class="demo-item">
            <p>功能：将数字转换为带货币符号的千分位格式（如12345.67 → "¥12,345.67"）</p>
            <input v-model.number="currencyInput" type="number" placeholder="输入数字（如12345.67）">
            <input v-model="currencySymbol" placeholder="货币符号（如¥）">
            <button @click="handleFormatCurrency">格式化</button>
            <p class="result">结果：{{ currencyResult }}</p>
          </div>
        </div>
      </section>

      <!-- 2. 数组操作 -->
      <section class="demo-card" id="数组操作">
        <h2>2. 数组操作</h2>
        
        <div class="demo-sub-card" id="数组乱序">
          <h3>2.1 数组乱序</h3>
          <div class="demo-item">
            <p>功能：随机打乱数组元素顺序（不修改原数组）</p>
            <p>原数组：{{ originArr }}</p>
            <button @click="handleArrScramble">乱序</button>
            <p class="result">结果：{{ scrambledArr }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="数组扁平化">
          <h3>2.2 数组扁平化</h3>
          <div class="demo-item">
            <p>功能：将嵌套数组转换为一维数组（如[1,[2,[3]]] → [1,2,3]）</p>
            <input v-model="flatInput" placeholder="输入嵌套数组（如 [1, [2, [3, 4], 5]]）">
            <button @click="handleFlatten">扁平化</button>
            <p class="result">结果：{{ flatResult }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="数组随机元素">
          <h3>2.3 随机获取数组元素</h3>
          <div class="demo-item">
            <p>功能：从数组中随机获取一个元素</p>
            <p>数组：{{ fruitArr }}</p>
            <button @click="handleSample">随机获取</button>
            <p class="result">结果：{{ sampleVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="数组数学计算">
          <h3>2.4 数组数学计算（最大值、最小值、平均值、求和）</h3>
          <div class="demo-item">
            <p>功能：计算数字数组的最大值、最小值、平均值和总和</p>
            <input v-model="numberArrayInput" placeholder="输入数字数组（如 [1,2,3,4,5]）">
            <button @click="handleArrayMath">计算</button>
            <p class="result">最大值：{{ arrayMath.max }}</p>
            <p class="result">最小值：{{ arrayMath.min }}</p>
            <p class="result">平均值：{{ arrayMath.average }}</p>
            <p class="result">总和：{{ arrayMath.sum }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="数组去重">
          <h3>2.5 数组去重</h3>
          <div class="demo-item">
            <p>功能：移除数组中的重复元素（支持基本类型）</p>
            <input v-model="uniqueArrayInput" placeholder="输入数组（如 [1,2,2,3,3,4]）">
            <button @click="handleUniqueArray">去重</button>
            <p class="result">结果：{{ uniqueArrayResult }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="数组排序">
          <h3>2.6 对象数组排序</h3>
          <div class="demo-item">
            <p>功能：根据对象的指定字段对数组排序（支持升序/降序）</p>
            <textarea v-model="sortArrayInput" placeholder='输入对象数组（如 [{"name":"张三","age":25},{"name":"李四","age":30}]）'></textarea>
            <input v-model="sortKey" placeholder="排序字段（如age）">
            <select v-model="sortOrder">
              <option value="asc">升序</option>
              <option value="desc">降序</option>
            </select>
            <button @click="handleSortArray">排序</button>
            <p class="result">结果：{{ sortArrayResult }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="数组过滤">
          <h3>2.7 对象数组过滤</h3>
          <div class="demo-item">
            <p>功能：筛选出对象数组中指定字段等于目标值的元素</p>
            <textarea v-model="filterArrayInput" placeholder='输入对象数组（如 [{"name":"张三","age":25},{"name":"李四","age":30}]）'></textarea>
            <input v-model="filterKey" placeholder="过滤字段（如age）">
            <input v-model="filterValue" placeholder="过滤值（如25）">
            <button @click="handleFilterArray">过滤</button>
            <p class="result">结果：{{ filterArrayResult }}</p>
          </div>
        </div>
      </section>

      <!-- 3. 字符串操作 -->
      <section class="demo-card" id="字符串操作">
        <h2>3. 字符串操作</h2>
        
        <div class="demo-sub-card" id="随机字符串">
          <h3>3.1 生成指定长度随机字符串</h3>
          <div class="demo-item">
            <p>功能：生成包含大小写字母和数字的随机字符串</p>
            <input v-model.number="strLen" type="number" placeholder="长度（如6）">
            <button @click="handleRandomStr">生成</button>
            <p class="result">结果：{{ randomStrVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="首字母大写">
          <h3>3.2 首字母大写</h3>
          <div class="demo-item">
            <p>功能：将字符串首字母转换为大写，其余不变（如hello → Hello）</p>
            <input v-model="firstLetterInput" placeholder="输入字符串（如hello）">
            <button @click="handleFirstLetterUpper">转换</button>
            <p class="result">结果：{{ firstLetterVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="手机号处理">
          <h3>3.3 手机号中间四位隐藏</h3>
          <div class="demo-item">
            <p>功能：将手机号中间四位替换为*（如13800138000 → 138****8000）</p>
            <input v-model="telInput" placeholder="输入手机号（如13800138000）">
            <button @click="handleTelFormat">转换</button>
            <p class="result">结果：{{ telVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="驼峰命名转换">
          <h3>3.4 驼峰转短横线（如 userName → user-name）</h3>
          <div class="demo-item">
            <p>功能：将驼峰命名转换为短横线分隔（如userNameAge → user-name-age）</p>
            <input v-model="kebabInput" placeholder="输入驼峰字符串（如userNameAge）">
            <button @click="handleKebabCase">转换</button>
            <p class="result">结果：{{ kebabVal }}</p>
          </div>
          
          <h3>3.5 短横线转驼峰（如 user-name → userName）</h3>
          <div class="demo-item">
            <p>功能：将短横线分隔转换为驼峰命名（如user-name-age → userNameAge）</p>
            <input v-model="camelInput" placeholder="输入短横线字符串（如user-name-age）">
            <button @click="handleCamelCase">转换</button>
            <p class="result">结果：{{ camelVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="全角半角转换">
          <h3>3.6 全角转半角（如 １２３ → 123）</h3>
          <div class="demo-item">
            <p>功能：将全角字符转换为半角字符（如１２３ａｂｃ → 123abc）</p>
            <input v-model="cdbInput" placeholder="输入全角字符（如１２３ａｂｃ）">
            <button @click="handleToCDB">转换</button>
            <p class="result">结果：{{ cdbVal }}</p>
          </div>
          
          <h3>3.7 半角转全角（如 123 → １２３）</h3>
          <div class="demo-item">
            <p>功能：将半角字符转换为全角字符（如123abc → １２３ａｂｃ）</p>
            <input v-model="dbcInput" placeholder="输入半角字符（如123abc）">
            <button @click="handleToDBC">转换</button>
            <p class="result">结果：{{ dbcVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="空格处理">
          <h3>3.8 去除所有空格</h3>
          <div class="demo-item">
            <p>功能：移除字符串中所有空格（包括中间空格）</p>
            <input v-model="trimAllInput" placeholder="输入带空格字符串（如  hello  world ）">
            <button @click="handleTrimAll">去除所有空格</button>
            <p class="result">结果：{{ trimAllVal }}</p>
          </div>
          
          <h3>3.9 去除前后空格</h3>
          <div class="demo-item">
            <p>功能：仅移除字符串首尾空格，保留中间空格</p>
            <input v-model="trimInput" placeholder="输入带前后空格字符串（如  hello world ）">
            <button @click="handleTrim">去除前后空格</button>
            <p class="result">结果：{{ trimVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="密码强度检测">
          <h3>3.10 密码强度检测</h3>
          <div class="demo-item">
            <p>功能：检测密码强度（1-5级，包含数字/字母/特殊字符越多强度越高）</p>
            <input v-model="passwordInput" placeholder="输入密码">
            <button @click="handleCheckPassword">检测强度</button>
            <p class="result">强度等级：{{ passwordStrength }} (最高5级)</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="字符串截取">
          <h3>3.11 字符串截取并添加省略号</h3>
          <div class="demo-item">
            <p>功能：截取指定长度字符串，超出部分用...代替</p>
            <input v-model="ellipsisStrInput" placeholder="输入字符串">
            <input v-model.number="ellipsisLengthInput" type="number" placeholder="截取长度（如10）">
            <button @click="handleEllipsis">截取</button>
            <p class="result">结果：{{ ellipsisResult }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="字符串生成">
          <h3>3.12 生成随机字符串</h3>
          <div class="demo-item">
            <p>功能：生成指定长度的纯随机字符串（包含大小写字母和数字）</p>
            <input v-model.number="randomStrLengthInput" type="number" placeholder="字符串长度（如10）">
            <button @click="handleGenerateRandomString">生成</button>
            <p class="result">结果：{{ randomStrResult }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="字符串反转">
          <h3>3.13 字符串反转</h3>
          <div class="demo-item">
            <p>功能：将字符串字符顺序反转（如hello → olleh）</p>
            <input v-model="reverseStrInput" placeholder="输入字符串（如hello world）">
            <button @click="handleReverseString">反转</button>
            <p class="result">结果：{{ reverseStrResult }}</p>
          </div>
        </div>
      </section>

      <!-- 4. 格式转化 -->
      <section class="demo-card" id="格式转化">
        <h2>4. 格式转化</h2>
        
        <div class="demo-sub-card" id="金额大写">
          <h3>4.1 数字转大写金额</h3>
          <div class="demo-item">
            <p>功能：将数字转换为中文大写金额（如1234.56 → 壹仟贰佰叁拾肆元伍角陆分）</p>
            <input v-model.number="amountInput" type="number" placeholder="输入金额（如1234.56）">
            <button @click="handleDigitUppercase">转换</button>
            <p class="result">结果：{{ amountVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="数字转中文">
          <h3>4.2 数字转中文数字</h3>
          <div class="demo-item">
            <p>功能：将阿拉伯数字转换为中文数字（如10086 → 一万零八十六）</p>
            <input v-model="chineseNumInput" placeholder="输入数字（如10086）">
            <button @click="handleIntToChinese">转换</button>
            <p class="result">结果：{{ chineseNumVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="颜色转换">
          <h3>4.3 RGB与十六进制颜色转换</h3>
          <div class="demo-item">
            <p>功能：在RGB和十六进制颜色格式之间相互转换</p>
            <div>
              <label>RGB: </label>
              <input v-model.number="rgb.r" type="number" min="0" max="255" placeholder="R（0-255）">
              <input v-model.number="rgb.g" type="number" min="0" max="255" placeholder="G（0-255）">
              <input v-model.number="rgb.b" type="number" min="0" max="255" placeholder="B（0-255）">
              <button @click="handleRgbToHex">转为十六进制</button>
            </div>
            <div>
              <label>十六进制: </label>
              <input v-model="hexColor" placeholder="#ffffff">
              <button @click="handleHexToRgb">转为RGB</button>
            </div>
            <p class="result">RGB转十六进制：{{ rgbResult }}</p>
            <p class="result">十六进制转RGB：{{ hexResult }}</p>
          </div>
        </div>
      </section>

      <!-- 5. 存储操作（localStorage + sessionStorage） -->
      <section class="demo-card" id="存储操作">
        <h2>5. 存储操作</h2>
        
        <div class="demo-sub-card" id="localStorage">
          <h3>5.1 localStorage 存储/读取/删除</h3>
          <div class="demo-item">
            <p>功能：操作localStorage（永久存储，除非手动删除）</p>
            <input v-model="localKey" placeholder="键名（如username）">
            <input v-model="localValue" placeholder="值（如张三）">
            <button @click="handleLocalSet">存储</button>
            <button @click="handleLocalGet">读取</button>
            <button @click="handleLocalRemove">删除</button>
            <p class="result">localStorage 结果：{{ localResult }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="sessionStorage">
          <h3>5.2 sessionStorage 存储/读取/删除</h3>
          <div class="demo-item">
            <p>功能：操作sessionStorage（会话级存储，关闭页面后失效）</p>
            <input v-model="sessionKey" placeholder="键名（如token）">
            <input v-model="sessionValue" placeholder="值（如abc123）">
            <button @click="handleSessionSet">存储</button>
            <button @click="handleSessionGet">读取</button>
            <button @click="handleSessionRemove">删除</button>
            <p class="result">sessionStorage 结果：{{ sessionResult }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="永久缓存">
          <h3>5.3 永久缓存 存储/读取/删除</h3>
          <div class="demo-item">
            <p>功能：封装的永久缓存（基于localStorage，自动处理JSON序列化）</p>
            <input v-model="permanentKey" placeholder="键名（如permanentData）">
            <input v-model="permanentValue" placeholder="值（如这是永久数据）">
            <button @click="handlePermanentSet">存储</button>
            <button @click="handlePermanentGet">读取</button>
            <button @click="handlePermanentRemove">删除</button>
            <p class="result">永久缓存结果：{{ permanentResult }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="带过期时间存储">
          <h3>5.4 带过期时间的localStorage</h3>
          <div class="demo-item">
            <p>功能：存储带过期时间的数据（过期后自动失效）</p>
            <input v-model="expireKey" placeholder="键名（如expireKey）">
            <input v-model="expireValue" placeholder="值（如expireValue）">
            <input v-model.number="expireTime" type="number" placeholder="过期时间(毫秒，如5000)">
            <button @click="handleSetExpireStorage">存储</button>
            <button @click="handleGetExpireStorage">读取</button>
            <p class="result">结果：{{ expireResult }}</p>
          </div>
        </div>
      </section>

      <!-- 6. Cookie 操作 -->
      <section class="demo-card" id="Cookie操作">
        <h2>6. Cookie 操作</h2>
        
        <div class="demo-sub-card" id="Cookie操作">
          <h3>6.1 Cookie 存储/读取/删除（过期天数）</h3>
          <div class="demo-item">
            <p>功能：操作Cookie（可设置过期时间，支持跨域限制）</p>
            <input v-model="cookieKey" placeholder="键名（如theme）">
            <input v-model="cookieValue" placeholder="值（如dark）">
            <input v-model.number="cookieExpire" type="number" placeholder="过期天数（如7）">
            <button @click="handleCookieSet">存储</button>
            <button @click="handleCookieGet">读取</button>
            <button @click="handleCookieDel">删除</button>
            <p class="result">Cookie 结果：{{ cookieResult }}</p>
          </div>
        </div>
      </section>

      <!-- 7. 格式校验 -->
      <section class="demo-card" id="格式校验">
        <h2>7. 格式校验</h2>
        
        <div class="demo-sub-card" id="身份证校验">
          <h3>7.1 身份证号校验</h3>
          <div class="demo-item">
            <p>功能：验证18位身份证号有效性（校验规则符合国家标准）</p>
            <input v-model="idCardInput" placeholder="输入身份证号（如110101199003071234）">
            <button @click="handleCheckIdCard">校验</button>
            <p class="result">结果：{{ idCardValid ? '有效' : '无效' }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="身份证信息">
          <h3>7.2 根据身份证号获取信息</h3>
          <div class="demo-item">
            <p>功能：从身份证号中提取生日和性别信息</p>
            <input v-model="idCardInfoInput" placeholder="输入身份证号（如110101199003071234）">
            <button @click="handleGetIdCardInfo">获取信息</button>
            <p class="result">生日：{{ idCardInfo.birth }}</p>
            <p class="result">性别：{{ idCardInfo.sex }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="中文检测">
          <h3>7.3 是否包含中文</h3>
          <div class="demo-item">
            <p>功能：检测字符串中是否包含中文字符</p>
            <input v-model="cnInput" placeholder="输入字符串（如Hello 世界）">
            <button @click="handleCheckCN">校验</button>
            <p class="result">结果：{{ hasCN ? '包含' : '不包含' }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="手机号校验">
          <h3>7.4 手机号校验</h3>
          <div class="demo-item">
            <p>功能：验证手机号格式（支持11位中国大陆手机号）</p>
            <input v-model="checkTelInput" placeholder="输入手机号（如13800138000）">
            <button @click="handleCheckTel">校验</button>
            <p class="result">结果：{{ telValid ? '有效' : '无效' }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="邮箱校验">
          <h3>7.5 邮箱校验</h3>
          <div class="demo-item">
            <p>功能：验证邮箱格式有效性（符合通用邮箱规则）</p>
            <input v-model="emailInput" placeholder="输入邮箱（如test@example.com）">
            <button @click="handleCheckEmail">校验</button>
            <p class="result">结果：{{ emailValid ? '有效' : '无效' }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="Emoji检测">
          <h3>7.6 是否包含 Emoji</h3>
          <div class="demo-item">
            <p>功能：检测字符串中是否包含Emoji表情</p>
            <input v-model="emojiInput" placeholder="输入内容（如Hello 😊）">
            <button @click="handleCheckEmoji">校验</button>
            <p class="result">结果：{{ hasEmoji ? '包含' : '不包含' }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="URL校验">
          <h3>7.7 URL有效性校验</h3>
          <div class="demo-item">
            <p>功能：验证URL地址格式是否有效（支持http/https等协议）</p>
            <input v-model="urlInput" placeholder="输入URL（如https://www.example.com）">
            <button @click="handleCheckUrl">校验</button>
            <p class="result">结果：{{ urlValid ? '有效' : '无效' }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="JSON校验">
          <h3>7.8 JSON字符串有效性校验</h3>
          <div class="demo-item">
            <p>功能：验证字符串是否为有效的JSON格式</p>
            <input v-model="jsonInput" placeholder="输入JSON字符串（如{\'name\'':\'张三\''}）">
            <button @click="handleCheckJson">校验</button>
            <p class="result">结果：{{ jsonValid ? '有效' : '无效' }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="空值校验">
          <h3>7.9 数据是否为空值校验</h3>
          <div class="demo-item">
            <p>功能：判断值是否为空（包括null/undefined/空字符串/空数组/空对象）</p>
            <input v-model="emptyValueInput" placeholder="输入任意值">
            <button @click="handleCheckEmpty">校验</button>
            <p class="result">结果：{{ isEmptyValue ? '为空' : '不为空' }}</p>
          </div>
        </div>
      </section>

      <!-- 8. URL 操作 -->
      <section class="demo-card" id="URL操作">
        <h2>8. URL 操作</h2>
        
        <div class="demo-sub-card" id="URL参数获取">
          <h3>8.1 获取当前 URL 参数</h3>
          <div class="demo-item">
            <p>功能：解析当前页面URL中的查询参数，返回键值对对象</p>
            <input v-model="handleGetUrl" placeholder="输入地址（如 https://example.com?name=张三&age=20">
            <button @click="handleGetUrlParams">获取</button>
            <p class="result">结果：{{ urlParams }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="对象转URL">
          <h3>8.2 对象转 URL 参数（如 {a:1,b:2} → a=1&b=2）</h3>
          <div class="demo-item">
            <p>功能：将对象转换为URL查询参数字符串（自动编码特殊字符）</p>
            <input v-model="urlObjInput" placeholder="输入对象（如 {a:1,b:2}）">
            <button @click="handleParams2Url">转换</button>
            <p class="result">结果：{{ urlParamsStr }}</p>
          </div>
        </div>
        <div class="demo-sub-card" id="URL参数修改">
          <h3>8.3 URL转对象</h3>
          <div class="demo-item">
            <p>功能：将URL转换为对象查询参数字符串（自动编码特殊字符）</p>
            <p>当前 URL：{{ currentUrl }}</p>
            <input v-model="urlParamsToObjData" placeholder="参数名（如：https://test.com?hobby=篮球&hobby=编程&tags=前端&tags=TypeScript）">
            <button @click="urlParamsToObj">修改</button>
            <p class="result">结果：{{ newUrlParamsToObj }}</p>
          </div>
        </div>
        <div class="demo-sub-card" id="URL参数修改">
          <h3>8.4 修改 URL 参数</h3>
          <div class="demo-item">
            <p>功能：修改URL中指定参数的值，返回新URL（不刷新页面）</p>
            <p>当前 URL：{{ currentUrl }}</p>
            <input v-model="urlParamKey" placeholder="参数名（如page）">
            <input v-model="urlParamVal" placeholder="新值（如2）">
            <button @click="handleReplaceUrlParam">修改</button>
            <p class="result">新 URL：{{ newUrl }}</p>
          </div>
        </div>
      </section>

      <!-- 9. 设备判断 -->
      <section class="demo-card" id="设备判断">
        <h2>9. 设备判断</h2>
        
        <div class="demo-sub-card" id="设备类型">
          <h3>9.1 当前设备类型</h3>
          <div class="demo-item">
            <p>功能：判断当前设备类型（如手机/平板/电脑）</p>
            <button @click="handleCheckDevice">检测</button>
            <p class="result">结果：{{ deviceType }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="系统类型">
          <h3>9.2 当前系统（Windows/Mac）</h3>
          <div class="demo-item">
            <p>功能：判断当前操作系统（如Windows/Mac/iOS/Android）</p>
            <button @click="handleCheckOs">检测</button>
            <p class="result">结果：{{ osType }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="浏览器类型">
          <h3>9.3 当前浏览器</h3>
          <div class="demo-item">
            <p>功能：判断当前浏览器类型及版本（如Chrome/Edge/Firefox）</p>
            <button @click="handleCheckBrowser">检测</button>
            <p class="result">结果：{{ browserInfo }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="设备信息">
          <h3>9.4 设备信息</h3>
          <div class="demo-item">
            <p>功能：获取设备相关信息（像素比/屏幕方向/是否移动设备）</p>
            <button @click="handleGetDeviceInfo">获取设备信息</button>
            <p class="result">设备像素比：{{ deviceInfo.pixelRatio }}</p>
            <p class="result">屏幕方向：{{ deviceInfo.orientation }}</p>
            <p class="result">是否移动设备：{{ deviceInfo.isMobile ? '是' : '否' }}</p>
          </div>
        </div>
      </section>

      <!-- 10. 浏览器操作 -->
      <section class="demo-card" id="浏览器操作">
        <h2>10. 浏览器操作</h2>
        
        <div class="demo-sub-card" id="滚动控制">
          <h3>10.1 滚动控制</h3>
          <div class="demo-item">
            <p>功能：控制页面滚动（到顶部/到底部/到指定元素）</p>
            <button @click="$tool.scrollToTop()">滚动到顶部</button>
            <button @click="$tool.scrollToBottom()">滚动到底部</button>
            <button @click="$tool.smoothScroll('#target')">滚动到目标元素</button>
          </div>
        </div>
        
        <div class="demo-sub-card" id="全屏控制">
          <h3>10.2 全屏控制</h3>
          <div class="demo-item">
            <p>功能：控制页面进入/退出全屏模式</p>
            <button @click="$tool.toFullScreen()">进入全屏</button>
            <button @click="$tool.exitFullscreen()">退出全屏</button>
          </div>
        </div>
        
        <div class="demo-sub-card" id="窗口尺寸">
          <h3>10.3 可视窗口尺寸</h3>
          <div class="demo-item">
            <p>功能：获取浏览器可视区域的宽度和高度</p>
            <button @click="handleGetClientSize">获取</button>
            <p class="result">宽度：{{ clientWidth }}px，高度：{{ clientHeight }}px</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="复制文本">
          <h3>10.4 复制文本到剪贴板</h3>
          <div class="demo-item">
            <p>功能：将指定文本复制到系统剪贴板（支持主流浏览器）</p>
            <input v-model="copyTextInput" placeholder="输入要复制的文本">
            <button @click="handleCopyText">复制</button>
            <p class="result">复制结果：{{ copyTextResult }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="读取剪贴板">
          <h3>10.5 读取剪贴板内容</h3>
          <div class="demo-item">
            <p>功能：读取系统剪贴板中的文本内容（需用户授权）</p>
            <button @click="handleReadClipboard">读取</button>
            <p class="result">剪贴板内容：{{ clipboardContent }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="图片懒加载">
          <h3>10.6 图片懒加载演示</h3>
          <div class="demo-item">
            <p>功能：图片进入可视区域时再加载（优化性能）</p>
            <button @click="handleLazyLoadImage">加载图片</button>
            <div class="image-container">
              <img ref="lazyImageRef" alt="懒加载图片" style="width: 200px; height: 200px; background: #f0f0f0;">
            </div>
          </div>
        </div>
        
        <div class="demo-sub-card" id="页面操作">
          <h3>10.7 页面操作</h3>
          <div class="demo-item">
            <p>功能：检测页面是否刷新/强制刷新页面</p>
            <button @click="handleCheckPageRefresh">检测是否刷新页面</button>
            <button @click="handleForceRefresh">强制刷新页面</button>
            <p class="result">页面是否刷新：{{ isPageRefresh ? '是' : '否' }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="链接操作">
          <h3>10.8 链接操作</h3>
          <div class="demo-item">
            <p>功能：打开内部/外部链接（外部链接自动添加noopener）</p>
            <button @click="handleOpenInternalLink">打开内部链接</button>
            <button @click="handleOpenExternalLink">打开外部链接</button>
          </div>
        </div>
        
        <div class="demo-sub-card" id="水印功能">
          <h3>10.9 水印功能</h3>
          <div class="demo-item">
            <p>功能：给页面添加/移除水印（防止截图泄露）</p>
            <input v-model="watermarkText" placeholder="输入水印文字">
            <button @click="handleAddWatermark">添加水印</button>
            <button @click="handleRemoveWatermark">移除水印</button>
          </div>
        </div>
        
        <div class="demo-sub-card" id="元素操作">
          <h3>10.10 元素操作</h3>
          <div class="demo-item">
            <p>功能：检测元素是否在视口内/获取元素位置</p>
            <button @click="handleCheckElementInViewport">检测元素是否在视口内</button>
            <button @click="handleGetElementOffset">获取元素位置</button>
            <p class="result">元素是否在视口内：{{ elementInViewport ? '是' : '否' }}</p>
            <p class="result">元素位置：top={{ elementOffset.top }}, left={{ elementOffset.left }}</p>
            <div ref="targetElementRef" style="margin-top: 20px; padding: 10px; background: #f0f0f0; width: 200px;">
              目标元素
            </div>
          </div>
        </div>
        
        <div class="demo-sub-card" id="文件操作">
          <h3>10.11 文件操作</h3>
          <div class="demo-item">
            <p>功能：将文本内容下载为指定文件名的文件</p>
            <input v-model="downloadFileName" placeholder="文件名（如example.txt）">
            <input v-model="downloadFileContent" placeholder="文件内容">
            <button @click="handleDownloadTextFile">下载文本文件</button>
          </div>
        </div>
        
        <div class="demo-sub-card" id="网络状态">
          <h3>10.12 网络状态</h3>
          <div class="demo-item">
            <p>功能：检测当前网络状态/监听网络状态变化</p>
            <button @click="handleCheckNetworkStatus">检测网络状态</button>
            <button @click="handleListenNetworkStatus">监听网络状态变化</button>
            <p class="result">当前网络状态：{{ isOnline ? '在线' : '离线' }}</p>
            <p class="result">网络状态变化：{{ networkStatusChange }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="浏览器通知">
          <h3>10.13 浏览器通知</h3>
          <div class="demo-item">
            <p>功能：显示浏览器桌面通知（需用户授权）</p>
            <input v-model="notificationTitle" placeholder="通知标题">
            <input v-model="notificationBody" placeholder="通知内容">
            <button @click="handleShowNotification">显示通知</button>
            <p class="result">通知权限：{{ notificationPermission }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="UUID生成">
          <h3>10.14 UUID生成</h3>
          <div class="demo-item">
            <p>功能：生成符合UUID v4标准的唯一标识符</p>
            <button @click="handleGenerateUUID">生成UUID</button>
            <p class="result">结果：{{ uuidResult }}</p>
          </div>
        </div>
        
        <div id="target" style="margin: 50px 0; padding: 20px; background: #f0f0f0;">
          目标滚动元素（id="target"）
        </div>
      </section>

      <!-- 11. 时间操作 -->
      <section class="demo-card" id="时间操作">
        <h2>11. 时间操作</h2>
        
        <div class="demo-sub-card" id="当前时间">
          <h3>11.1 当前时间（默认格式）</h3>
          <div class="demo-item">
            <p>功能：获取当前时间（默认格式：YYYY-MM-DD HH:mm:ss）</p>
            <button @click="handleGetNowTime">获取</button>
            <p class="result">结果：{{ nowTimeVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="时间格式化">
          <h3>11.2 自定义时间格式化</h3>
          <div class="demo-item">
            <p>功能：将时间格式化为指定格式（支持YYYY/MM/DD/HH/mm/ss等占位符）</p>
            <input v-model="timeFormat" placeholder="输入格式（如 YYYY-MM-DD HH:mm:ss）">
            <button @click="handleFormatTime">格式化</button>
            <p class="result">结果：{{ formattedTimeVal }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="时间范围计算">
          <h3>11.3 时间范围计算</h3>
          <div class="demo-item">
            <p>功能：获取指定时间范围（如今天/本周/本月的起止时间）</p>
            <select v-model="dateRangeType">
              <option value="today">今天</option>
              <option value="week">本周</option>
              <option value="month">本月</option>
              <option value="threeMonths">近三个月</option>
              <option value="year">今年</option>
              <option value="threeYears">近三年</option>
            </select>
            <button @click="handleGetDateRange">获取时间范围</button>
            <p class="result">开始时间：{{ dateRange.start }}</p>
            <p class="result">结束时间：{{ dateRange.end }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="前后时间范围">
          <h3>11.4 前后时间范围计算</h3>
          <div class="demo-item">
            <p>功能：获取当前时间前后的时间范围（如过去一周/未来一个月）</p>
            <select v-model="aroundDateRangeType">
              <option value="week">一周</option>
              <option value="month">一个月</option>
              <option value="threeMonths">三个月</option>
              <option value="year">一年</option>
              <option value="threeYears">三年</option>
            </select>
            <select v-model="aroundDateRangeDirection">
              <option value="past">过去</option>
              <option value="future">将来</option>
              <option value="both">前后</option>
            </select>
            <button @click="handleGetDateRangeAround">获取时间范围</button>
            <p class="result">开始时间：{{ aroundDateRange.start }}</p>
            <p class="result">结束时间：{{ aroundDateRange.end }}</p>
          </div>
        </div>
      </section>

      <!-- 12. 通用操作 -->
      <section class="demo-card" id="通用操作">
        <h2>12. 通用操作</h2>
        
        <div class="demo-sub-card" id="防抖节流">
          <h3>12.1 防抖函数（输入后 500ms 触发）</h3>
          <div class="demo-item">
            <p>功能：触发后延迟指定时间执行，若期间再次触发则重新计时（如搜索输入）</p>
            <input v-model="debounceInput" @input="handleDebounce" placeholder="输入测试">
            <p class="result">防抖结果：{{ debounceResult }}</p>
          </div>
          
          <h3>12.2 节流函数（1s 内最多触发 1 次）</h3>
          <div class="demo-item">
            <p>功能：指定时间内最多执行一次（如滚动事件）</p>
            <button @click="handleThrottle">快速点击</button>
            <p class="result">节流触发次数：{{ throttleCount }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="数据类型判断">
          <h3>12.3 数据类型判断</h3>
          <div class="demo-item">
            <p>功能：准确判断数据类型（如array/object/date/regExp等）</p>
            <input v-model="typeInput" placeholder="输入任意值（如[]、{}、123）">
            <button @click="handleGetType">判断</button>
            <p class="result">类型：{{ typeResult }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="对象深拷贝">
          <h3>12.4 对象深拷贝</h3>
          <div class="demo-item">
            <p>功能：深拷贝对象/数组（解决引用类型赋值问题，支持循环引用）</p>
            <input v-model="cloneInput" placeholder="输入对象（如 {a:1,b:[2]}）">
            <button @click="handleDeepClone">拷贝</button>
            <p class="result">原对象：{{ cloneInput }}</p>
            <p class="result">拷贝后（修改不影响原对象）：{{ clonedObj }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="阻止冒泡">
          <h3>12.5 阻止冒泡</h3>
          <div class="demo-item">
            <p>功能：阻止事件冒泡（子元素事件不触发父元素事件）</p>
            <div class="parent" @click="handleParentClick">
              父元素（点击触发）
              <button class="child" @click="handleChildClick($event)">子按钮（阻止冒泡）</button>
            </div>
            <p class="result">冒泡日志：{{ bubbleLog }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="函数式编程">
          <h3>12.6 函数式编程工具</h3>
          <div class="demo-item">
            <p>功能：柯里化/函数组合/管道（函数式编程常用工具）</p>
            <button @click="handleCurry">柯里化示例</button>
            <button @click="handleCompose">组合函数示例</button>
            <button @click="handlePipe">管道函数示例</button>
            <p class="result">柯里化结果：{{ curryResult }}</p>
            <p class="result">组合函数结果：{{ composeResult }}</p>
            <p class="result">管道函数结果：{{ pipeResult }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="性能监控">
          <h3>12.7 性能监控</h3>
          <div class="demo-item">
            <p>功能：获取页面加载总时间（从开始到完全加载完成）</p>
            <button @click="handleGetPageLoadTime">获取页面加载时间</button>
            <p class="result">页面加载时间：{{ pageLoadTime }}ms</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="文件处理">
          <h3>12.8 文件处理</h3>
          <div class="demo-item">
            <p>功能：将字节数格式化为易读的文件大小（如1.5MB）</p>
            <input v-model.number="fileSizeInput" type="number" placeholder="文件大小(字节，如1572864)">
            <button @click="handleFormatFileSize">格式化文件大小</button>
            <p class="result">格式化结果：{{ formattedFileSize }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="对象操作">
          <h3>12.9 对象操作</h3>
          <div class="demo-item">
            <p>功能：获取对象键/值/判断对象是否为空</p>
            <textarea v-model="objectInput" placeholder='输入对象（如 {"name":"张三","age":25}）'></textarea>
            <button @click="handleGetObjectKeys">获取键</button>
            <button @click="handleGetObjectValues">获取值</button>
            <button @click="handleCheckObjectEmpty">检查是否为空</button>
            <p class="result">键：{{ objectKeys }}</p>
            <p class="result">值：{{ objectValues }}</p>
            <p class="result">是否为空：{{ isObjectEmpty ? '是' : '否' }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="DOM操作">
          <h3>12.10 DOM操作</h3>
          <div class="demo-item">
            <p>功能：给DOM元素添加/移除/检查CSS类</p>
            <div ref="domElementRef" class="demo-dom-element" style="padding: 10px; background: #f0f0f0;">
              DOM元素示例
            </div>
            <button @click="handleAddClass">添加CSS类</button>
            <button @click="handleRemoveClass">移除CSS类</button>
            <button @click="handleHasClass">检查是否有CSS类</button>
            <input v-model="cssClassName" placeholder="CSS类名（如highlight）">
            <p class="result">是否有该CSS类：{{ hasCssClass ? '是' : '否' }}</p>
          </div>
        </div>
        
        <div class="demo-sub-card" id="等待函数">
          <h3>12.11 等待函数</h3>
          <div class="demo-item">
            <p>功能：异步等待指定时间（替代setTimeout的Promise版本）</p>
            <input v-model.number="sleepTime" type="number" placeholder="等待时间(毫秒，如1000)">
            <button @click="handleSleep">等待</button>
            <p class="result">等待状态：{{ sleepStatus }}</p>
          </div>
        </div>
      </section>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, onMounted } from 'vue';

// 获取全局工具函数（确保$tool已在全局注册）
const { proxy } = getCurrentInstance() as { proxy: { $tool: any } };
const $tool = proxy.$tool;

// 目录分类定义
const categories = [
  { id: '数字操作', name: '数字操作' },
  { id: '数组操作', name: '数组操作' },
  { id: '字符串操作', name: '字符串操作' },
  { id: '格式转化', name: '格式转化' },
  { id: '存储操作', name: '存储操作' },
  { id: 'Cookie操作', name: 'Cookie 操作' },
  { id: '格式校验', name: '格式校验' },
  { id: 'URL操作', name: 'URL 操作' },
  { id: '设备判断', name: '设备判断' },
  { id: '浏览器操作', name: '浏览器操作' },
  { id: '时间操作', name: '时间操作' },
  { id: '通用操作', name: '通用操作' }
];

// 子目录分类定义
const subCategories = [
  // 数字操作子分类
  { id: '随机数生成', name: '随机数生成', parentIndex: 0, subIndex: 0 },
  { id: '数字格式化', name: '数字格式化', parentIndex: 0, subIndex: 1 },
  
  // 数组操作子分类
  { id: '数组乱序', name: '数组乱序', parentIndex: 1, subIndex: 0 },
  { id: '数组扁平化', name: '数组扁平化', parentIndex: 1, subIndex: 1 },
  { id: '数组随机元素', name: '数组随机元素', parentIndex: 1, subIndex: 2 },
  { id: '数组数学计算', name: '数组数学计算', parentIndex: 1, subIndex: 3 },
  { id: '数组去重', name: '数组去重', parentIndex: 1, subIndex: 4 },
  { id: '数组排序', name: '数组排序', parentIndex: 1, subIndex: 5 },
  { id: '数组过滤', name: '数组过滤', parentIndex: 1, subIndex: 6 },
  
  // 字符串操作子分类
  { id: '随机字符串', name: '随机字符串', parentIndex: 2, subIndex: 0 },
  { id: '首字母大写', name: '首字母大写', parentIndex: 2, subIndex: 1 },
  { id: '手机号处理', name: '手机号处理', parentIndex: 2, subIndex: 2 },
  { id: '驼峰命名转换', name: '驼峰命名转换', parentIndex: 2, subIndex: 3 },
  { id: '全角半角转换', name: '全角半角转换', parentIndex: 2, subIndex: 4 },
  { id: '空格处理', name: '空格处理', parentIndex: 2, subIndex: 5 },
  { id: '密码强度检测', name: '密码强度检测', parentIndex: 2, subIndex: 6 },
  { id: '字符串截取', name: '字符串截取', parentIndex: 2, subIndex: 7 },
  { id: '字符串生成', name: '字符串生成', parentIndex: 2, subIndex: 8 },
  { id: '字符串反转', name: '字符串反转', parentIndex: 2, subIndex: 9 },
  
  // 格式转化子分类
  { id: '金额大写', name: '金额大写', parentIndex: 3, subIndex: 0 },
  { id: '数字转中文', name: '数字转中文', parentIndex: 3, subIndex: 1 },
  { id: '颜色转换', name: '颜色转换', parentIndex: 3, subIndex: 2 },
  
  // 存储操作子分类
  { id: 'localStorage', name: 'localStorage', parentIndex: 4, subIndex: 0 },
  { id: 'sessionStorage', name: 'sessionStorage', parentIndex: 4, subIndex: 1 },
  { id: '永久缓存', name: '永久缓存', parentIndex: 4, subIndex: 2 },
  { id: '带过期时间存储', name: '带过期时间存储', parentIndex: 4, subIndex: 3 },
  
  // Cookie操作子分类
  { id: 'Cookie操作', name: 'Cookie操作', parentIndex: 5, subIndex: 0 },
  
  // 格式校验子分类
  { id: '身份证校验', name: '身份证校验', parentIndex: 6, subIndex: 0 },
  { id: '身份证信息', name: '身份证信息', parentIndex: 6, subIndex: 1 },
  { id: '中文检测', name: '中文检测', parentIndex: 6, subIndex: 2 },
  { id: '手机号校验', name: '手机号校验', parentIndex: 6, subIndex: 3 },
  { id: '邮箱校验', name: '邮箱校验', parentIndex: 6, subIndex: 4 },
  { id: 'Emoji检测', name: 'Emoji检测', parentIndex: 6, subIndex: 5 },
  { id: 'URL校验', name: 'URL校验', parentIndex: 6, subIndex: 6 },
  { id: 'JSON校验', name: 'JSON校验', parentIndex: 6, subIndex: 7 },
  { id: '空值校验', name: '空值校验', parentIndex: 6, subIndex: 8 },
  
  // URL操作子分类
  { id: 'URL参数获取', name: 'URL参数获取', parentIndex: 7, subIndex: 0 },
  { id: '对象转URL', name: '对象转URL', parentIndex: 7, subIndex: 1 },
  { id: 'URL参数修改', name: 'URL参数修改', parentIndex: 7, subIndex: 2 },
  
  // 设备判断子分类
  { id: '设备类型', name: '设备类型', parentIndex: 8, subIndex: 0 },
  { id: '系统类型', name: '系统类型', parentIndex: 8, subIndex: 1 },
  { id: '浏览器类型', name: '浏览器类型', parentIndex: 8, subIndex: 2 },
  { id: '设备信息', name: '设备信息', parentIndex: 8, subIndex: 3 },
  
  // 浏览器操作子分类
  { id: '滚动控制', name: '滚动控制', parentIndex: 9, subIndex: 0 },
  { id: '全屏控制', name: '全屏控制', parentIndex: 9, subIndex: 1 },
  { id: '窗口尺寸', name: '窗口尺寸', parentIndex: 9, subIndex: 2 },
  { id: '复制文本', name: '复制文本', parentIndex: 9, subIndex: 3 },
  { id: '读取剪贴板', name: '读取剪贴板', parentIndex: 9, subIndex: 4 },
  { id: '图片懒加载', name: '图片懒加载', parentIndex: 9, subIndex: 5 },
  { id: '页面操作', name: '页面操作', parentIndex: 9, subIndex: 6 },
  { id: '链接操作', name: '链接操作', parentIndex: 9, subIndex: 7 },
  { id: '水印功能', name: '水印功能', parentIndex: 9, subIndex: 8 },
  { id: '元素操作', name: '元素操作', parentIndex: 9, subIndex: 9 },
  { id: '文件操作', name: '文件操作', parentIndex: 9, subIndex: 10 },
  { id: '网络状态', name: '网络状态', parentIndex: 9, subIndex: 11 },
  { id: '浏览器通知', name: '浏览器通知', parentIndex: 9, subIndex: 12 },
  { id: 'UUID生成', name: 'UUID生成', parentIndex: 9, subIndex: 13 },
  
  // 时间操作子分类
  { id: '当前时间', name: '当前时间', parentIndex: 10, subIndex: 0 },
  { id: '时间格式化', name: '时间格式化', parentIndex: 10, subIndex: 1 },
  { id: '时间范围计算', name: '时间范围计算', parentIndex: 10, subIndex: 2 },
  { id: '前后时间范围', name: '前后时间范围', parentIndex: 10, subIndex: 3 },
  
  // 通用操作子分类
  { id: '防抖节流', name: '防抖节流', parentIndex: 11, subIndex: 0 },
  { id: '数据类型判断', name: '数据类型判断', parentIndex: 11, subIndex: 1 },
  { id: '对象深拷贝', name: '对象深拷贝', parentIndex: 11, subIndex: 2 },
  { id: '阻止冒泡', name: '阻止冒泡', parentIndex: 11, subIndex: 3 },
  { id: '函数式编程', name: '函数式编程', parentIndex: 11, subIndex: 4 },
  { id: '性能监控', name: '性能监控', parentIndex: 11, subIndex: 5 },
  { id: '文件处理', name: '文件处理', parentIndex: 11, subIndex: 6 },
  { id: '对象操作', name: '对象操作', parentIndex: 11, subIndex: 7 },
  { id: 'DOM操作', name: 'DOM操作', parentIndex: 11, subIndex: 8 },
  { id: '等待函数', name: '等待函数', parentIndex: 11, subIndex: 9 }
];

// 滚动到指定区域（平滑滚动）
const scrollToSection = (id: string) => {
  const element = document.getElementById(id);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' });
  }
};

// 1. 数字操作
const numMin = ref<number>(1);
const numMax = ref<number>(100);
const randomNumVal = ref<number>(0);
// 生成[min, max]随机整数
const handleRandomNum = () => {
  if (numMin.value > numMax.value) {
    [numMin.value, numMax.value] = [numMax.value, numMin.value]; // 交换min和max
  }
  randomNumVal.value = $tool.randomNum(numMin.value, numMax.value);
};

const thousandInput = ref<string>('1234567');
const thousandVal = ref<string>('');
// 数字千分位格式化
const handleThousandFormat = () => {
  thousandVal.value = $tool.formatThousands(thousandInput.value) || '格式错误';
};

const formatNumInput = ref<number>(123.456);
const formatDigitsInput = ref<number>(2);
const formatNumResult = ref<string>('');
// 数字格式化为指定位数小数
const handleFormatNumber = () => {
  if (formatDigitsInput.value < 0) formatDigitsInput.value = 0;
  formatNumResult.value = $tool.formatNumber(formatNumInput.value, formatDigitsInput.value);
};

const currencyInput = ref<number>(12345.67);
const currencySymbol = ref<string>('¥');
const currencyResult = ref<string>('');
// 数字格式化为货币形式
const handleFormatCurrency = () => {
  currencyResult.value = $tool.formatCurrency(currencyInput.value, currencySymbol.value);
};

// 2. 数组操作
const originArr = [1, 2, 3, 4, 5];
const scrambledArr = ref<number[]>([]);
// 数组乱序
const handleArrScramble = () => {
  scrambledArr.value = $tool.arrScrambling([...originArr]); // 传入副本避免影响原数组
};

const flatInput = ref<string>('[1, [2, [3, 4], 5]]');
const flatResult = ref<any[]>([]);
// 数组扁平化
const handleFlatten = () => {
  try {
    const arr = JSON.parse(flatInput.value);
    if (!Array.isArray(arr)) throw new Error('不是数组');
    flatResult.value = $tool.flatten(arr);
  } catch (e) {
    flatResult.value = ['输入格式错误（请输入合法数组）'];
  }
};

const fruitArr = ['苹果', '香蕉', '橙子', '草莓'];
const sampleVal = ref<string>('');
// 随机获取数组元素
const handleSample = () => {
  sampleVal.value = $tool.sample(fruitArr) || '数组为空';
};

const numberArrayInput = ref<string>('[1,2,3,4,5]');
const arrayMath = ref<{ max: number; min: number; average: number; sum: number }>({
  max: 0,
  min: 0,
  average: 0,
  sum: 0
});
// 数组数学计算
const handleArrayMath = () => {
  try {
    const arr = JSON.parse(numberArrayInput.value);
    if (!Array.isArray(arr) || arr.some(item => typeof item !== 'number')) {
      throw new Error('不是数字数组');
    }
    arrayMath.value = {
      max: $tool.arrayMax(arr),
      min: $tool.arrayMin(arr),
      average: $tool.arrayAverage(arr),
      sum: $tool.arraySum(arr)
    };
  } catch (e) {
    console.error('数组格式错误', e);
    arrayMath.value = { max: NaN, min: NaN, average: NaN, sum: NaN };
  }
};

const uniqueArrayInput = ref<string>('[1,2,2,3,3,4]');
const uniqueArrayResult = ref<string>('');
// 数组去重
const handleUniqueArray = () => {
  try {
    const arr = JSON.parse(uniqueArrayInput.value);
    if (!Array.isArray(arr)) throw new Error('不是数组');
    uniqueArrayResult.value = JSON.stringify($tool.uniqueArray(arr));
  } catch (e) {
    uniqueArrayResult.value = '数组格式错误';
  }
};

const sortArrayInput = ref<string>('[{"name":"张三","age":25},{"name":"李四","age":30},{"name":"王五","age":20}]');
const sortKey = ref<string>('age');
const sortOrder = ref<'asc' | 'desc'>('asc');
const sortArrayResult = ref<string>('');
// 对象数组排序
const handleSortArray = () => {
  try {
    const arr = JSON.parse(sortArrayInput.value);
    if (!Array.isArray(arr) || !arr.every(item => typeof item === 'object')) {
      throw new Error('不是对象数组');
    }
    sortArrayResult.value = JSON.stringify($tool.sortBy(arr, sortKey.value, sortOrder.value));
  } catch (e) {
    sortArrayResult.value = '数组或字段格式错误';
  }
};

const filterArrayInput = ref<string>('[{"name":"张三","age":25},{"name":"李四","age":30},{"name":"王五","age":25}]');
const filterKey = ref<string>('age');
const filterValue = ref<any>(25);
const filterArrayResult = ref<string>('');
// 对象数组过滤
const handleFilterArray = () => {
  try {
    const arr = JSON.parse(filterArrayInput.value);
    if (!Array.isArray(arr) || !arr.every(item => typeof item === 'object')) {
      throw new Error('不是对象数组');
    }
    filterArrayResult.value = JSON.stringify($tool.filterBy(arr, filterKey.value, filterValue.value));
  } catch (e) {
    filterArrayResult.value = '数组或字段格式错误';
  }
};

// 3. 字符串操作
const strLen = ref<number>(6);
const randomStrVal = ref<string>('');
// 生成指定长度随机字符串
const handleRandomStr = () => {
  if (strLen.value < 1) strLen.value = 1;
  randomStrVal.value = $tool.randomString(strLen.value);
};

const firstLetterInput = ref<string>('hello');
const firstLetterVal = ref<string>('');
// 首字母大写
const handleFirstLetterUpper = () => {
  firstLetterVal.value = $tool.firstLetterUpper(firstLetterInput.value);
};

const telInput = ref<string>('13800138000');
const telVal = ref<string>('');
// 手机号中间四位隐藏
const handleTelFormat = () => {
  telVal.value = $tool.telFormat(telInput.value) || '手机号格式错误';
};

const kebabInput = ref<string>('userNameAge');
const kebabVal = ref<string>('');
// 驼峰转短横线
const handleKebabCase = () => {
  kebabVal.value = $tool.getKebabCase(kebabInput.value);
};

const camelInput = ref<string>('user-name-age');
const camelVal = ref<string>('');
// 短横线转驼峰
const handleCamelCase = () => {
  camelVal.value = $tool.getCamelCase(camelInput.value);
};

const cdbInput = ref<string>('１２３ａｂｃ');
const cdbVal = ref<string>('');
// 全角转半角
const handleToCDB = () => {
  cdbVal.value = $tool.toCDB(cdbInput.value);
};

const dbcInput = ref<string>('123abc');
const dbcVal = ref<string>('');
// 半角转全角
const handleToDBC = () => {
  dbcVal.value = $tool.toDBC(dbcInput.value);
};

const trimAllInput = ref<string>('  hello  world  ');
const trimAllVal = ref<string>('');
// 去除所有空格
const handleTrimAll = () => {
  trimAllVal.value = $tool.trimAll(trimAllInput.value);
};

const trimInput = ref<string>('  hello world  ');
const trimVal = ref<string>('');
// 去除前后空格
const handleTrim = () => {
  trimVal.value = $tool.trim(trimInput.value);
};

const passwordInput = ref<string>('Test123!@#');
const passwordStrength = ref<number>(0);
// 密码强度检测
const handleCheckPassword = () => {
  passwordStrength.value = $tool.checkPasswordStrength(passwordInput.value);
};

const ellipsisStrInput = ref<string>('这是一个很长的字符串用于测试截取功能');
const ellipsisLengthInput = ref<number>(10);
const ellipsisResult = ref<string>('');
// 字符串截取并添加省略号
const handleEllipsis = () => {
  if (ellipsisLengthInput.value < 0) ellipsisLengthInput.value = 0;
  ellipsisResult.value = $tool.ellipsis(ellipsisStrInput.value, ellipsisLengthInput.value);
};

const randomStrLengthInput = ref<number>(10);
const randomStrResult = ref<string>('');
// 生成随机字符串
const handleGenerateRandomString = () => {
  if (randomStrLengthInput.value < 1) randomStrLengthInput.value = 1;
  randomStrResult.value = $tool.generateRandomString(randomStrLengthInput.value);
};

const reverseStrInput = ref<string>('hello world');
const reverseStrResult = ref<string>('');
// 字符串反转
const handleReverseString = () => {
  reverseStrResult.value = $tool.reverseString(reverseStrInput.value);
};

// 4. 格式转化
const amountInput = ref<number>(1234.56);
const amountVal = ref<string>('');
// 数字转大写金额
const handleDigitUppercase = () => {
  amountVal.value = $tool.digitUppercase(amountInput.value) || '金额格式错误';
};

const chineseNumInput = ref<string>('10086');
const chineseNumVal = ref<string>('');
// 数字转中文数字
const handleIntToChinese = () => {
  chineseNumVal.value = $tool.intToChinese(chineseNumInput.value) || '数字格式错误';
};

const rgb = ref<{ r: number; g: number; b: number }>({ r: 255, g: 0, b: 0 });
const hexColor = ref<string>('#ff0000');
const rgbResult = ref<string>('');
const hexResult = ref<string>('');
// RGB转十六进制
const handleRgbToHex = () => {
  // 确保RGB值在0-255范围内
  const r = Math.min(255, Math.max(0, rgb.value.r || 0));
  const g = Math.min(255, Math.max(0, rgb.value.g || 0));
  const b = Math.min(255, Math.max(0, rgb.value.b || 0));
  rgbResult.value = $tool.rgbToHex(r, g, b);
};
// 十六进制转RGB
const handleHexToRgb = () => {
  const result = $tool.hexToRgb(hexColor.value);
  hexResult.value = result ? `r:${result.r}, g:${result.g}, b:${result.b}` : '转换失败（请输入合法十六进制颜色）';
};

// 5. 存储操作
const localKey = ref<string>('username');
const localValue = ref<string>('张三');
const localResult = ref<string>('');
// localStorage存储
const handleLocalSet = () => {
  if (localKey.value) $tool.localStorageSet(localKey.value, localValue.value);
};
// localStorage读取
const handleLocalGet = () => {
  localResult.value = $tool.localStorageGet(localKey.value) || '无数据';
};
// localStorage删除
const handleLocalRemove = () => {
  if (localKey.value) $tool.localStorageRemove(localKey.value);
  localResult.value = '';
};

const sessionKey = ref<string>('token');
const sessionValue = ref<string>('abc123');
const sessionResult = ref<string>('');
// sessionStorage存储
const handleSessionSet = () => {
  if (sessionKey.value) $tool.sessionStorageSet(sessionKey.value, sessionValue.value);
};
// sessionStorage读取
const handleSessionGet = () => {
  sessionResult.value = $tool.sessionStorageGet(sessionKey.value) || '无数据';
};
// sessionStorage删除
const handleSessionRemove = () => {
  if (sessionKey.value) $tool.sessionStorageRemove(sessionKey.value);
  sessionResult.value = '';
};

const permanentKey = ref<string>('permanentData');
const permanentValue = ref<string>('这是永久数据');
const permanentResult = ref<string>('');
// 永久缓存存储
const handlePermanentSet = () => {
  if (permanentKey.value) $tool.permanentStorageSet(permanentKey.value, permanentValue.value);
};
// 永久缓存读取
const handlePermanentGet = () => {
  permanentResult.value = $tool.permanentStorageGet(permanentKey.value) || '无数据';
};
// 永久缓存删除
const handlePermanentRemove = () => {
  if (permanentKey.value) $tool.permanentStorageRemove(permanentKey.value);
  permanentResult.value = '';
};

const expireKey = ref<string>('expireKey');
const expireValue = ref<string>('expireValue');
const expireTime = ref<number>(5000); // 5秒过期
const expireResult = ref<string>('');
// 带过期时间存储
const handleSetExpireStorage = () => {
  if (expireKey.value && expireTime.value > 0) {
    $tool.setStorageWithExpire(expireKey.value, expireValue.value, expireTime.value);
    expireResult.value = '存储成功（5秒后过期）';
  }
};
// 读取带过期时间的存储
const handleGetExpireStorage = () => {
  const result = $tool.getStorageWithExpire(expireKey.value);
  expireResult.value = result !== null ? result : '无数据或已过期';
};

// 6. Cookie 操作
const cookieKey = ref<string>('theme');
const cookieValue = ref<string>('dark');
const cookieExpire = ref<number>(7);
const cookieResult = ref<string>('');
// Cookie存储
const handleCookieSet = () => {
  if (cookieKey.value && cookieExpire.value > 0) {
    $tool.setCookie(cookieKey.value, cookieValue.value, cookieExpire.value);
  }
};
// Cookie读取
const handleCookieGet = () => {
  cookieResult.value = $tool.getCookie(cookieKey.value) || '无数据';
};
// Cookie删除
const handleCookieDel = () => {
  if (cookieKey.value) $tool.delCookie(cookieKey.value);
  cookieResult.value = '';
};

// 7. 格式校验
const idCardInput = ref<string>('110101199003071234');
const idCardValid = ref<boolean>(false);
// 身份证号校验
const handleCheckIdCard = () => {
  idCardValid.value = $tool.checkCardNo(idCardInput.value);
};

const idCardInfoInput = ref<string>('110101199003071234');
const idCardInfo = ref<{ birth: string; sex: string }>({ birth: '', sex: '' });
// 根据身份证号获取信息
const handleGetIdCardInfo = () => {
  idCardInfo.value = {
    birth: $tool.getBirthByIdCard(idCardInfoInput.value) || '无效身份证号',
    sex: $tool.getSexByIdCard(idCardInfoInput.value) || '无效身份证号'
  };
};

const cnInput = ref<string>('Hello 世界');
const hasCN = ref<boolean>(false);
// 是否包含中文
const handleCheckCN = () => {
  hasCN.value = $tool.haveCNChars(cnInput.value);
};

const checkTelInput = ref<string>('13800138000');
const telValid = ref<boolean>(false);
// 手机号校验
const handleCheckTel = () => {
  telValid.value = $tool.isTel(checkTelInput.value);
};

const emailInput = ref<string>('test@example.com');
const emailValid = ref<boolean>(false);
// 邮箱校验
const handleCheckEmail = () => {
  emailValid.value = $tool.isEmail(emailInput.value);
};

const emojiInput = ref<string>('Hello 😊');
const hasEmoji = ref<boolean>(false);
// 是否包含Emoji
const handleCheckEmoji = () => {
  hasEmoji.value = $tool.isEmojiCharacter(emojiInput.value);
};

const urlInput = ref<string>('https://www.example.com');
const urlValid = ref<boolean>(false);
// URL有效性校验
const handleCheckUrl = () => {
  urlValid.value = $tool.isValidURL(urlInput.value);
};

const jsonInput = ref<string>('{"name":"张三","age":25}');
const jsonValid = ref<boolean>(false);
// JSON字符串有效性校验
const handleCheckJson = () => {
  jsonValid.value = $tool.isValidJSON(jsonInput.value);
};

const emptyValueInput = ref<string>('');
const isEmptyValue = ref<boolean>(false);
// 数据是否为空值校验
const handleCheckEmpty = () => {
  isEmptyValue.value = $tool.isEmpty(emptyValueInput.value);
};

// 8. URL 操作
const urlParams = ref<Record<string, any>>({});
const handleGetUrl = ref<string>('');
// 获取当前URL参数
const handleGetUrlParams = () => {
  urlParams.value = $tool.getUrlParams(handleGetUrl.value);
  
};

const urlObjInput = ref<string>('{ "name": "张三", "age": 20 }');
const urlParamsStr = ref<string>('');
// 对象转URL参数
const handleParams2Url = () => {
  try {
    const obj = JSON.parse(urlObjInput.value);
    urlParamsStr.value = $tool.objToUrlParams(obj);
  } catch (e) {
    urlParamsStr.value = '输入格式错误（请输入合法对象）';
  }
};

// URL转对象
const urlParamsToObjData = ref<string>('');
const newUrlParamsToObj = ref<string>('');
const urlParamsToObj = ()=>{

    newUrlParamsToObj.value = $tool.urlParamsToObj(urlParamsToObjData.value);

}

const currentUrl = ref<string>('');
const urlParamKey = ref<string>('page');
const urlParamVal = ref<string>('2');
const newUrl = ref<string>('');
// 初始化当前URL
onMounted(() => {
  currentUrl.value = window.location.href;
});
// 修改URL参数
const handleReplaceUrlParam = () => {
  if (urlParamKey.value) {
    newUrl.value = $tool.replaceUrlParam(urlParamKey.value, urlParamVal.value) || '修改失败';
  }
};

// 9. 设备判断
const deviceType = ref<string>('');
// 当前设备类型
const handleCheckDevice = () => {
  deviceType.value = $tool.getDeviceType();
};

const osType = ref<string>('');
// 当前系统
const handleCheckOs = () => {
  osType.value = $tool.getOsType();
};

const browserInfo = ref<string>('');
// 当前浏览器
const handleCheckBrowser = () => {
  const info = $tool.getExplorerInfo();
  browserInfo.value = info ? `${info.type} v${info.version}` : '无法识别浏览器';
};

const deviceInfo = ref<{ pixelRatio: number; orientation: string; isMobile: boolean }>({
  pixelRatio: 1,
  orientation: '',
  isMobile: false
});
// 获取设备信息
const handleGetDeviceInfo = () => {
  deviceInfo.value = {
    pixelRatio: $tool.getDevicePixelRatio(),
    orientation: $tool.getScreenOrientation() || '未知',
    isMobile: $tool.isMobile()
  };
};

// 10. 浏览器操作
const clientWidth = ref<number>(0);
const clientHeight = ref<number>(0);
// 可视窗口尺寸
const handleGetClientSize = () => {
  clientWidth.value = $tool.getPageViewWidth();
  clientHeight.value = $tool.getClientHeight();
};

const copyTextInput = ref<string>('这是要复制的文本');
const copyTextResult = ref<string>('');
// 复制文本到剪贴板
const handleCopyText = async () => {
  try {
    const result = await $tool.copyText(copyTextInput.value);
    copyTextResult.value = result ? '复制成功' : '复制失败';
  } catch (e) {
    copyTextResult.value = '复制失败（可能是浏览器不支持）';
  }
};

const clipboardContent = ref<string>('');
// 读取剪贴板内容
const handleReadClipboard = async () => {
  try {
    clipboardContent.value = await $tool.readClipboard();
  } catch (e) {
    clipboardContent.value = '读取失败（需用户授权或浏览器不支持）';
  }
};

const lazyImageRef = ref<HTMLImageElement | null>(null);
// 图片懒加载
const handleLazyLoadImage = () => {
  if (lazyImageRef.value) {
    // 示例图片URL（实际使用时替换为真实图片地址）
    $tool.lazyLoadImage(
      lazyImageRef.value, 
      'https://picsum.photos/200/200', 
      'https://via.placeholder.com/200x200?text=Loading' // 占位图
    );
  }
};

const isPageRefresh = ref<boolean>(false);
// 检测是否刷新页面
const handleCheckPageRefresh = () => {
  isPageRefresh.value = $tool.isPageRefresh();
};

// 强制刷新页面
const handleForceRefresh = () => {
  $tool.forceRefresh();
};

// 打开内部链接
const handleOpenInternalLink = () => {
  $tool.openInternalLink('/tables'); // 替换为实际内部路由
};

// 打开外部链接
const handleOpenExternalLink = () => {
  $tool.openExternalLink('https://github.com'); // 替换为实际外部链接
};

const watermarkText = ref<string>('水印文字');
// 添加水印
const handleAddWatermark = () => {
  $tool.addWatermark(watermarkText.value || '默认水印');
};

// 移除水印
const handleRemoveWatermark = () => {
  $tool.removeWatermark();
};

const targetElementRef = ref<HTMLElement | null>(null);
const elementInViewport = ref<boolean>(false);
const elementOffset = ref<{ top: number; left: number }>({ top: 0, left: 0 });
// 检测元素是否在视口内
const handleCheckElementInViewport = () => {
  if (targetElementRef.value) {
    elementInViewport.value = $tool.isElementInViewport(targetElementRef.value);
  }
};
// 获取元素位置
const handleGetElementOffset = () => {
  if (targetElementRef.value) {
    elementOffset.value = $tool.getElementOffset(targetElementRef.value);
  }
};

const downloadFileName = ref<string>('example.txt');
const downloadFileContent = ref<string>('这是下载的文本内容');
// 下载文本文件
const handleDownloadTextFile = () => {
  if (downloadFileName.value && downloadFileContent.value) {
    $tool.downloadTextAsFile(downloadFileContent.value, downloadFileName.value);
  }
};

const isOnline = ref<boolean>(true);
const networkStatusChange = ref<string>('');
// 检测网络状态
const handleCheckNetworkStatus = () => {
  isOnline.value = $tool.isOnline();
};
// 监听网络状态变化
const handleListenNetworkStatus = () => {
  networkStatusChange.value = '开始监听...';
  $tool.onNetworkStatusChange((status: boolean) => {
    networkStatusChange.value = `网络状态变化：${status ? '在线' : '离线'}`;
    isOnline.value = status;
  });
};

const notificationTitle = ref<string>('通知标题');
const notificationBody = ref<string>('通知内容');
const notificationPermission = ref<string>('');
// 显示浏览器通知
const handleShowNotification = async () => {
  try {
    // 先请求通知权限
    const permission = await Notification.requestPermission();
    notificationPermission.value = permission;
    if (permission === 'granted') {
      await $tool.showNotification(notificationTitle.value, {
        body: notificationBody.value,
        icon: '/favicon.ico' // 替换为实际图标路径
      });
    }
  } catch (e) {
    notificationPermission.value = '显示失败（浏览器不支持或未授权）';
  }
};

const uuidResult = ref<string>('');
// 生成UUID
const handleGenerateUUID = () => {
  uuidResult.value = $tool.generateUUID();
};

// 11. 时间操作
const nowTimeVal = ref<string>('');
// 当前时间（默认格式）
const handleGetNowTime = () => {
  nowTimeVal.value = $tool.nowTime();
};

const timeFormat = ref<string>('YYYY-MM-DD HH:mm:ss');
const formattedTimeVal = ref<string>('');
// 自定义时间格式化
const handleFormatTime = () => {
  formattedTimeVal.value = $tool.dateFormater(timeFormat.value) || '格式错误';
};

const dateRangeType = ref<'today' | 'week' | 'month' | 'threeMonths' | 'year' | 'threeYears'>('today');
const dateRange = ref<{ start: string, end: string }>({ start: '', end: '' });
// 时间范围计算
const handleGetDateRange = () => {
  const range = $tool.getDateRange(dateRangeType.value);
  dateRange.value = {
    start: range.start?.toString() || '',
    end: range.end?.toString() || ''
  };
};

const aroundDateRangeType = ref<'week' | 'month' | 'threeMonths' | 'year' | 'threeYears'>('week');
const aroundDateRangeDirection = ref<'past' | 'future' | 'both'>('both');
const aroundDateRange = ref<{ start: string, end: string }>({ start: '', end: '' });
// 前后时间范围计算
const handleGetDateRangeAround = () => {
  const range = $tool.getDateRangeAround(aroundDateRangeType.value, aroundDateRangeDirection.value);
  aroundDateRange.value = {
    start: range.start?.toString() || '',
    end: range.end?.toString() || ''
  };
};

// 12. 通用操作
const debounceInput = ref<string>('');
const debounceResult = ref<string>('');
// 防抖函数（输入后500ms触发）
const handleDebounce = $tool.debounce((e: Event) => {
  const value = (e.target as HTMLInputElement).value;
  debounceResult.value = `输入：${value}（${new Date().toLocaleTimeString()}）`;
}, 500);

const throttleCount = ref<number>(0);
// 节流函数（1s内最多触发1次）
const handleThrottle = $tool.throttle(() => {
  throttleCount.value++;
}, 1000);

const typeInput = ref<string>('[]');
const typeResult = ref<string>('');
// 数据类型判断
const handleGetType = () => {
  try {
    const value = JSON.parse(typeInput.value);
    typeResult.value = $tool.getType(value);
  } catch (e) {
    // 非JSON格式值直接判断（如字符串、数字）
    typeResult.value = $tool.getType(typeInput.value);
  }
};

const cloneInput = ref<string>('{ "name": "测试", "list": [1, 2, 3] }');
const clonedObj = ref<any>({});
// 对象深拷贝
const handleDeepClone = () => {
  try {
    const obj = JSON.parse(cloneInput.value);
    const clone = $tool.deepClone(obj);
    // 修改拷贝后的对象，验证深拷贝效果
    if (Array.isArray(clone.list)) clone.list.push(4);
    clonedObj.value = clone;
  } catch (e) {
    clonedObj.value = '输入格式错误（请输入合法对象）';
  }
};

const bubbleLog = ref<string>('');
// 父元素点击事件
const handleParentClick = () => {
  bubbleLog.value = '父元素事件触发';
};
// 子元素点击事件（阻止冒泡）
const handleChildClick = (e: Event) => {
  $tool.stopPropagation(e);
  bubbleLog.value = '子元素事件触发（已阻止冒泡）';
};

// 函数式编程工具示例
const curryResult = ref<string>('');
const composeResult = ref<string>('');
const pipeResult = ref<string>('');

// 柯里化示例（add(2)(3) = 5）
const add = (a: number) => (b: number) => a + b;
const handleCurry = () => {
  const curriedAdd = $tool.curry(add);
  curryResult.value = `curriedAdd(2)(3) = ${curriedAdd(2)(3)}`;
};

// 组合函数示例（先执行toUpperCase，再执行addExclamation）
const toUpperCase = (str: string) => str.toUpperCase();
const addExclamation = (str: string) => str + '!';
const handleCompose = () => {
  const composed = $tool.compose(addExclamation, toUpperCase);
  composeResult.value = `composed('hello') = ${composed('hello')}`; // 结果：HELLO!
};

// 管道函数示例（先执行toUpperCase，再执行addExclamation，与compose顺序一致）
const handlePipe = () => {
  const piped = $tool.pipe(toUpperCase, addExclamation);
  pipeResult.value = `piped('hello') = ${piped('hello')}`; // 结果：HELLO!
};

const pageLoadTime = ref<number | string>('');
// 获取页面加载时间
const handleGetPageLoadTime = () => {
  const time = $tool.getPageLoadTime();
  pageLoadTime.value = time !== null ? time : '浏览器不支持performance API';
};

const fileSizeInput = ref<number>(1024 * 1024 * 1.5); // 1.5MB
const formattedFileSize = ref<string>('');
// 格式化文件大小
const handleFormatFileSize = () => {
  if (fileSizeInput.value < 0) fileSizeInput.value = 0;
  formattedFileSize.value = $tool.formatFileSize(fileSizeInput.value);
};

// 对象操作
const objectInput = ref<string>('{"name":"张三","age":25}');
const objectKeys = ref<string[]>([]);
const objectValues = ref<any[]>([]);
const isObjectEmpty = ref<boolean>(false);
// 获取对象键
const handleGetObjectKeys = () => {
  try {
    const obj = JSON.parse(objectInput.value);
    if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
      throw new Error('不是纯对象');
    }
    objectKeys.value = $tool.keys(obj);
  } catch (e) {
    objectKeys.value = [];
  }
};
// 获取对象值
const handleGetObjectValues = () => {
  try {
    const obj = JSON.parse(objectInput.value);
    if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
      throw new Error('不是纯对象');
    }
    objectValues.value = $tool.values(obj);
  } catch (e) {
    objectValues.value = [];
  }
};
// 检查对象是否为空
const handleCheckObjectEmpty = () => {
  try {
    const obj = JSON.parse(objectInput.value);
    if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
      throw new Error('不是纯对象');
    }
    isObjectEmpty.value = $tool.isObjectEmpty(obj);
  } catch (e) {
    isObjectEmpty.value = true;
  }
};

// DOM操作
const domElementRef = ref<HTMLElement | null>(null);
const cssClassName = ref<string>('highlight');
const hasCssClass = ref<boolean>(false);
// 添加CSS类
const handleAddClass = () => {
  if (domElementRef.value && cssClassName.value) {
    $tool.addClass(domElementRef.value, cssClassName.value);
    // 添加强调样式（示例）
    const style = document.createElement('style');
    style.textContent = `.highlight { border: 2px solid #42b983; }`;
    document.head.appendChild(style);
  }
};
// 移除CSS类
const handleRemoveClass = () => {
  if (domElementRef.value && cssClassName.value) {
    $tool.removeClass(domElementRef.value, cssClassName.value);
  }
};
// 检查是否有CSS类
const handleHasClass = () => {
  if (domElementRef.value && cssClassName.value) {
    hasCssClass.value = $tool.hasClass(domElementRef.value, cssClassName.value);
  }
};

// 等待函数
const sleepTime = ref<number>(1000);
const sleepStatus = ref<string>('');
const handleSleep = async () => {
  if (sleepTime.value < 0) sleepTime.value = 0;
  sleepStatus.value = '等待中...';
  await $tool.sleep(sleepTime.value);
  sleepStatus.value = `等待了 ${sleepTime.value} 毫秒`;
};

</script>

<style scoped>
.all-tools-demo {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.toc-container {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.toc-container h2 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
}

.toc-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
  margin-bottom: 20px;
}

.toc-sub-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 8px;
}

.toc-item, .toc-sub-item {
  padding: 8px 12px;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.toc-item:hover, .toc-sub-item:hover {
  background: #42b983;
  color: white;
}

.toc-sub-item {
  font-size: 13px;
  padding: 6px 10px;
}

.demo-container {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.demo-card {
  border: 1px solid #eee;
  border-radius: 8px;
  background: #fff;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.demo-sub-card {
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  background: #fafafa;
  padding: 15px;
  margin-bottom: 20px;
  transition: box-shadow 0.2s;
}

.demo-sub-card:hover {
  box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}

.demo-sub-card:last-child {
  margin-bottom: 0;
}

.demo-sub-card h3 {
  margin: 0 0 15px 0;
  color: #555;
  font-size: 16px;
  border-bottom: 1px dashed #eee;
  padding-bottom: 8px;
}

.demo-item {
  margin: 15px 0;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 4px;
}

input, select, textarea {
  padding: 6px 10px;
  margin: 0 8px 8px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 100px;
  font-size: 14px;
}

textarea {
  min-width: 200px;
  min-height: 60px;
  resize: vertical;
}

button {
  padding: 6px 12px;
    margin: 0 8px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
}

button:hover {
  background: #359e75;
}

.result {
  margin: 10px 0;
  padding: 8px;
  color: #333;
  background: #f0f0f0;
  border-radius: 4px;
  word-break: break-all;
}

.parent {
  padding: 20px;
  background: #e8f4ea;
  border-radius: 4px;
}

.child {
  margin-top: 10px;
  background: #2ecc71;
}

h1, h2, h3 {
  color: #333;
}

h1 {
  font-size: 24px;
  margin-bottom: 30px;
  color: #2c3e50;
}

h2 {
  font-size: 20px;
  margin: 10px 0 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

h3 {
  font-size: 16px;
  margin: 10px 0 15px;
}

.image-container {
  margin-top: 10px;
}
</style>